<template>
  <div class="login_bg">
    <div class="login_main">
      <div class="login_config">

      </div>
      <div class="login-form">
        <div class="login-header">
          <div class="logo" style="background: white">
            <img alt="送水公司登录" width="80" src="images/logo3.png">
            <label >送水公司后台管理系统</label>
          </div>
          <h2>登录</h2>
        </div>
        <el-form ref="loginForm" :model="loginFormModel" :rules="loginFormRules" size="large">
          <el-form-item prop="email">
            <el-input ref="email" v-model="loginFormModel.account" placeholder="请输入用户名">
              <template #prefix>
                <el-icon class="el-input__icon"><User /></el-icon>
              </template>
              <template #append>
                <!-- 用来显示记住的用户名 -->
                <el-select ref="roleSelect" style="width: 130px" @change="selectChanged">
                  <el-option v-for="account of accounts" :key="account.key" :value="account.key"></el-option>
<!--                  <el-option value="admin"></el-option>-->
<!--                  <el-option value="user"></el-option>-->
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="pass">
            <el-input clearable show-password v-model="loginFormModel.password" placeholder="请输入密码">
              <template #prefix>
                <el-icon class="el-input__icon"><Lock /></el-icon>
              </template>

            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input clearable v-model="loginFormModel.code" placeholder="请输入验证码">
              <template #append>
                <div style="width: 90px;height: 40px;cursor: pointer;display:table-cell;text-align: center;margin: 0 auto" v-html="codeImageHTML" @click="freshCode"></div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-row>
              <el-col :span="12"><el-checkbox label="记住我" v-model="loginFormModel.autologin"></el-checkbox></el-col>
<!--              <el-col :span="12" style="text-align: right"><el-button type="text">忘记密码？</el-button> </el-col>-->
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" round @click="submitForm">登录</el-button>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div class="login-oauth">
          <el-button style="width:32px; height:32px;border: none;">

          </el-button>
        </div>
      </div>
    </div>
  </div>

</template>

<script>

export default {
  name: 'LoginView',
  data(){
    return {
      codeImageHTML:'',   //验证码图片的HTML代码
      accounts:[],          //用来保存本地记录的账户
      autologin: false,  //不自动登录
      userType: 'admin',
      //登录表单的数据模型，对应服务端的loginDTO
      loginFormModel: {
        account: '',      //'test@qq.com',
        password: '',       //'123456',
        code: '',
        codeUid: '',

      },
      //表单验证规则
      loginFormRules: {
        account: [
          {required: true, message: "请输入账号", trigger: 'blur'}
        ],
        password: {
          required: true, message: "请输入登录密码", trigger: 'blur'
        }
      }

    }
  },
  methods: {
    resetForm: function(){
      this.loginFormModel.account = '';
      this.loginFormModel.password = '';
      this.$refs.account.focus();
    },
    submitForm: function(){
      console.log("表单提交事件",this.loginFormModel);
      //1 是否通过表单验证规则的验证
      this.$refs.loginForm.validate(valid=>{
        if (!valid)return;
        if (this.loginFormModel.autologin){  //如果用户选择了记住密码
          let value=`${this.loginFormModel.account}=${this.loginFormModel.password}`;
          localStorage.setItem(this.loginFormModel.account,value);
        }
        //2 异步提交登录数据  表单数据的验证：email==teset@qq.com & pass==123456 &code=??? & codeUid=？？？
        //需要把json对象转化成formData的数据格式  引入666的库--qs库，qs库需要安装
        let thiz = this;
        this.axios.post('/administrator/login', this.loginFormModel)
            .then(function(user){
              thiz.axios.defaults.headers.common['Authorization'] = user.token;//放在axios进行提交
              //Authorization是我们自己取的名字，在服务端也要用到，进行全局的拦截和验证
              localStorage.setItem('token', user.token);
              sessionStorage.setItem('loginUser', JSON.stringify(user));
              thiz.$router.replace({path: '/client'});
            });
          //3. 页面跳转到用户个人中心页面-需要自行创建页面并配置路由
          //thiz.$router.replace({path: '/'});
      });
    },
    selectChanged:function (value){
      //找到accounts对应的账户
      let content=this.accounts.find(account=>account.key==value).value;
      //将获取到的值分别填入文本表单元素中
      this.loginFormModel.account=content.split("=")[0];
      this.loginFormModel.password=content.split("=")[1];
    },
    freshCode:function (){
      this.axios.get("/code/login").then(result => {

        //拼接HTML字符串
        //this.codeImageHTML=result.data.code;
        this.loginFormModel.codeUid=result.codeUid;
        //通过验证码生成图片
        this.codeImageHTML="";
        for(let char of result.code){
          let red = this.getRandomNum(0, 255);
          let green = this.getRandomNum(0, 255);
          let blue = this.getRandomNum(0, 255);
          let rotate = this.getRandomNum(-30, 30);
          let marginX = this.getRandomNum(0, 5);
          this.codeImageHTML += `
            <span style="font-weight: bold;
                color:rgb(${red}, ${green}, ${blue});
                transform: rotate(${rotate} deg);
                display: inline-block;
                margin-left:${marginX}px;
                margin-top: 0 auto;

                ">
                ${char}
            </span>
          `;
        }
      });
    },
    getRandomNum: function(minNum, maxNum) {
      return Math.floor(Math.random() * maxNum + minNum);
    },
    //初始化方法
    init: function(){
      //1、读取localstorage，加载本地存储的密码
      for (let i=0;i<localStorage.length;i++){
        let key=localStorage.key(i);
        let value=localStorage.getItem(key);
        //将本地存储的账户信息添加到accounts数组中方便显示
        this.accounts.push({key,value});
      }
      //2、请求并显示验证码
      this.freshCode();
    },
  },

  mounted: function() {
    this.init();

    //在这里调用初始化方法
    //console.log("Vue挂载成功！");
  }
}

</script>

<style scoped>
.login_bg {width: 100%;height: 100%;background: #fff;display: flex;}
.login_main {flex: 1;overflow: auto;display:flex;}
.login-form {width: 400px;margin: auto;padding:20px 0;}
.login-header {margin-bottom: 20px;}
.login-header .logo {display: flex;align-items: center;}
.login-header .logo img {width: 35px;height: 35px;vertical-align: bottom;margin-right: 10px;}
.login-header .logo label {font-size: 24px;}
.login-header h2 {font-size: 24px;font-weight: bold;margin-top: 50px;}
.login-oauth {display: flex;justify-content:space-around;}
.login-form .el-divider {margin-top:40px;}

.login_config {position: absolute;top:20px;right: 20px;}


</style>